package org.example.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import java.util.Random;

@Aspect
public class MyAspect {

    // 前置增强
    @Before("execution(* org.example.service.OrderService.*(..))")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

    // 后置增强（仅限 add, delete）
    @After("execution(* org.example.service.OrderService.add(..)) || execution(* org.example.service.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 返回值增强
    @AfterReturning(value = "execution(* org.example.service.OrderService.*(..))", returning = "result")
    public void afterReturningAdvice(Object result) {
        System.out.println("方法返回值: " + result);
    }

    // 环绕增强 (统计执行时间)
    @Around("execution(* org.example.service.OrderService.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        System.out.println("方法执行时间: " + (end - start) + " ms");
        return result;
    }

    // 权限校验 (仅 add, delete 前执行)
    @Before("execution(* org.example.service.OrderService.add(..)) || execution(* org.example.service.OrderService.delete(..))")
    public void checkPermission() {
        int flag = new java.util.Random().nextInt(2); // 0 或 1
        if (flag == 0) {
            System.out.println("权限校验通过，可以执行操作");
        } else {
            System.out.println("无权限执行该操作!");
            throw new RuntimeException("无权限执行该操作!");
        }
    }

}
